package com.microboot.interceptor;

import jakarta.xml.soap.SOAPException;
import jakarta.xml.soap.SOAPHeader;
import jakarta.xml.soap.SOAPMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.saaj.SAAJInInterceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.springframework.stereotype.Component;
import org.w3c.dom.NodeList;

@Component
@Slf4j
public class WebServiceAuthInterceptor extends AbstractPhaseInterceptor<SoapMessage> {

    private static final String USER_NAME = "longxian";
    private static final String USER_PASSWORD = "root123";
    private SAAJInInterceptor saa = new SAAJInInterceptor();//创建拦截器

    public WebServiceAuthInterceptor() {
        super(Phase.PRE_PROTOCOL);
        super.getAfter().add(SAAJInInterceptor.class.getName()); //添加拦截器
    }

    @Override
    public void handleMessage(SoapMessage mssage) throws Fault {
        SOAPMessage soapMessage = mssage.getContent(SOAPMessage.class);//获取指定消息
        if(soapMessage == null){ //没有消息内容
            this.saa.handleMessage(mssage);//直接走默认处理
            soapMessage = mssage.getContent(SOAPMessage.class);//尝试获取消息
        }
        SOAPHeader header = null; //SOAP头信息
        try{
            header = soapMessage.getSOAPHeader();//通过消息获取头信息
        }catch (SOAPException e){
            e.printStackTrace();
        }

        //没有头信息
        if(null == header){
            throw  new Fault(new IllegalAccessException("找不到Header信息，无法实现用户认证处理！"));
        }

        //SOAP是基于XML文件结构进行传输的，所以如果想要获取认证信息就必须进行相关结构约定
        NodeList usernameNodeList = header.getElementsByTagName("username");
        NodeList passwordNodeList = header.getElementsByTagName("password");

        if(null == usernameNodeList || usernameNodeList.getLength()<1){
            throw  new Fault(new IllegalAccessException("找不到Header信息，无法实现用户认证处理！"));
        }

        if(null == passwordNodeList || passwordNodeList.getLength()<1){
            throw  new Fault(new IllegalAccessException("找不到Header信息，无法实现用户认证处理！"));
        }

        String username = usernameNodeList.item(0).getTextContent().trim(); //获取用户名称
        String password = passwordNodeList.item(0).getTextContent().trim(); //获取用户密码

        log.info("认证用户账户：{}，密码：{}",username,password);

        //如果用户名称、密码通工程配置一致，则认证通过
        if(USER_NAME.equals(username) && USER_PASSWORD.equals(password)){
            log.info("用户访问认证成功!");
        }else {
            log.info("用户认证失败!");
            SOAPException soapException = new SOAPException("用户认证失败！");
            throw new Fault(soapException);
        }
    }
}
